package io.gitee.yth.design.pattern.test.core.pattern.behavioral.memento;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * @author yth
 * @since 2023-05-01-18:57
 */
public class Caretaker {

    private static final Caretaker instance = new Caretaker();

    public static Caretaker getInstance() {
        return instance;
    }

    private Caretaker() {
    }

    private final HashMap<Class<?>, List<Memento>> history = new HashMap<>();

    public Optional<Memento> get(Class<?> originator, int index) {
        return Optional.ofNullable(history.get(originator))
                .map(e -> index < e.size() ? e : null)
                .map(e -> e.get(index));
    }

    public void save(Class<?> originator, Memento memento) {
        final List<Memento> mementos = history.computeIfAbsent(
                originator, (k) -> new ArrayList<>());
        mementos.add(memento);
    }

    public Optional<Memento> getLatest(Class<?> originator) {
        return Optional.ofNullable(history.get(originator))
                .map(e -> e.isEmpty() ? null : e)
                .map(e -> e.get(e.size() - 1));
    }

    public Optional<Memento> remove(Class<?> originator, int index) {
        return Optional.ofNullable(history.get(originator))
                .map(e -> e.remove(index));
    }

    public Optional<Memento> popLatest(Class<?> originator) {
        return Optional.ofNullable(history.get(originator))
                .map(e -> e.isEmpty() ? null : e)
                .map(e -> e.remove(e.size() - 1));
    }

}
